package _dp_base;

import java.util.List;

/**
 * 139. 单词拆分
 */
public class No139 {
    private String s;
    private List<String> wordDict;
    private Boolean[] cache;

    /**
     * 1. 递归
     */
    public boolean wordBreak1(String s, List<String> wordDict) {
        this.s = s;
        this.wordDict = wordDict;
        int n = s.length();
        this.cache = new Boolean[n];

        return dfs(n - 1);
    }

    private boolean dfs(int i) {
        if (i < 0) return true;
        else if (cache[i] != null) return cache[i];

        for (int j = i; j >= 0; j--) {
            // 拆分出来的单词可以匹配
            if (wordDict.contains(s.substring(j, i + 1)) && dfs(j - 1)) return cache[i] = true;
        }
        // 这里是关键，找遍了0~i也没能完全匹配，标记从i结尾不能找到
        return cache[i] = false;
    }

    /**
     * 2. 迭代
     */
    public boolean wordBreak2(String s, List<String> wordDict) {
        int n = s.length();

        boolean[] f = new boolean[n + 1];
        f[0] = true;
        label:
        for (int i = 0; i < n; i++) {
            for (int j = i; j >= 0; j--) {
                // 拆分出来的单词可以匹配
                if (wordDict.contains(s.substring(j, i + 1)) && f[j]) {
                    f[i + 1] = true;
                    continue label;
                }
            }
            // 这里是关键，找遍了0~i也没能完全匹配，标记从i结尾不能找到
            f[i + 1] = false;
        }

        return f[n];
    }

    /**
     * 2.x 另一种思路的背包算法
     */
    public boolean wordBreak2x(String s, List<String> wordDict) {
        int n = s.length();

        boolean[] f = new boolean[n + 1];
        f[0] = true;

        for (int i = 1; i <= n; i++) {
            for (String word : wordDict) {
                int len = word.length();
                if (i >= len && f[i - len] && word.equals(s.substring(i - len, i))) {
                    f[i] = true;
                    break;
                }
            }
        }

        return f[n];
    }
}
